package com.baidu.manager.common.validator;

import com.baidu.manager.common.exception.JqlException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @Author: jql
 * @description: TODO(hibernate - validator校验工具类)
 * @Date: Created by 11:22 2018/4/13
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws JqlException 校验不通过，JqlException
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws JqlException {

        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("<br>");
            }
            throw new JqlException(msg.toString());
        }
    }

}
